package com.hkd.forum.controller;

import com.hkd.forum.common.AppResult;
import com.hkd.forum.common.ResultCode;
import com.hkd.forum.config.AppConfig;
import com.hkd.forum.exception.ApplicationException;
import com.hkd.forum.model.Article;
import com.hkd.forum.model.Board;
import com.hkd.forum.model.User;
import com.hkd.forum.service.IArticleService;
import com.hkd.forum.service.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    private IBoardService boardService;
    @Autowired
    private IArticleService articleService;

    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("板块ID") @RequestParam("boardId") @NonNull Long boardId,
                            @ApiParam("标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NonNull String content){

        //校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            //用户已禁言
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + "UserId =" + user.getId() + " 被禁言");
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //板块的校验
        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            //抛出异常
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }

        //封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());

        // 文章创建
        articleService.create(article);

        // 文章创建成功
        log.info("文章创建成功，UserId =" + user.getId() + " boardId =" + boardId);

        // 返回成功
        return AppResult.success();

    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块Id") @RequestParam(value = "boardId",required = false) Long boardId ){
        List<Article> articles;
        if(boardId == null){
            //用户没传入boardId实现全部查询
            articles = articleService.selectAll();
        }else {
            articles = articleService.selectAllByBoardId(boardId);
        }

        if(articles == null){
            articles = new ArrayList<>();
        }
        //相应结果
        return AppResult.success(articles);
    }
    @ApiOperation("获取帖子Id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
        //从session获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service获取帖子详情
        Article article = articleService.selectDetailById(id);
        //判断结果 非空校验
        if(article == null){
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if(user.getId() == article.getUserId()){
            //标志位
            article.setOwn(true);
        }

        //返回结果
        return AppResult.success(article);

    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子Id") @RequestParam @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam @NonNull String title,
                            @ApiParam("帖子正文") @RequestParam @NonNull String content){
        //获取当前登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验用户状态
        if(user.getState() == 1){
            //用户被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        Article article = articleService.selectById(id);
        if(article == null ){
            //贴子不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是不是作者
        if(user.getId() != article.getUserId()){
            //用户不是作者
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //判断帖子的状态
        if(article.getState() == 1 || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //修改帖子
        articleService.modify(id, title, content);

        //打印日志
        log.info("Article更新成功， ArticleId= "+id+" userId= "+user.getId() +" .");

        //返回成功
        return AppResult.success();

    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request, @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id){
        //获取user对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 直接调用service
        articleService.thumbsUpById(id);
        //返回结果
        return AppResult.success();
    }
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request, @ApiParam("帖⼦Id") @RequestParam("id") @NonNull Long id){
        //获取user对象
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取帖子详情
        Article article = articleService.selectById(id);

        if(article == null){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }

        if(article.getDeleteState() == 1 || article.getState() == 1){
            //打印日志
            log.warn(ResultCode.FAILED_ARTICLE_BANNED.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        //校验当前用户是否为作者
        if(user.getId() != article.getUserId()){
            return  AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }

        //调用service
        articleService.deleteById(id);
        return AppResult.success();
    }

    @ApiOperation("获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,@ApiParam("用户Id") @RequestParam(value = "userId",required = false) Long userId){

        if(userId == null){
            //获取user对象
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articles = articleService.selectByUserId(userId);
        //返回结果
        return AppResult.success(articles);

    }
}
